package com.example.demo01;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.exifinterface.media.ExifInterface;
import com.example.demo01.entity.ExifInfo;
import com.example.demo01.picture_frame.FrameUtils;
import com.example.demo01.picture_frame.frame.DefaultFrame;

import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {
    private TextView exifInfoTextView;
    private FrameLayout frameContainer;
    private static final int PERMISSION_REQUEST_CODE = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frameContainer = findViewById(R.id.frameContainer);

        exifInfoTextView = findViewById(R.id.exifInfoTextView);
        Button openGalleryButton = findViewById(R.id.openGalleryButton);

        openGalleryButton.setOnClickListener(v -> checkPermissionsAndOpenGallery());
    }

    // 检查权限并打开相册
    private void checkPermissionsAndOpenGallery() {
        // Android 13 及以上版本使用 READ_MEDIA_IMAGES 权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_MEDIA_IMAGES}, PERMISSION_REQUEST_CODE);
        } else {
            openGallery();
        }
    }

    // 打开相册
    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        galleryLauncher.launch(intent);
    }

    // 相册选择结果处理
    private final ActivityResultLauncher<Intent> galleryLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
            Uri selectedImageUri = result.getData().getData();
            try {
                if (selectedImageUri != null) {
                    displayExifInfo(selectedImageUri);
                }
            } catch (IOException e) {
                Toast.makeText(this, "读取 EXIF 信息失败", Toast.LENGTH_SHORT).show();
                Log.e("ExifExample", "Error reading EXIF data", e);
            }
        }
    });

    // 显示图片的 EXIF 信息
    private void displayExifInfo(android.net.Uri imageUri) throws IOException {
        try (InputStream inputStream = getContentResolver().openInputStream(imageUri)) {
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            if (bitmap != null) {
                bitmap = rotateBitmapIfRequired(bitmap, imageUri);
                Log.i("MainActivity", "Image size: " + bitmap.getWidth() + "x" + bitmap.getHeight());
                //
                FrameUtils.useFrame(bitmap,frameContainer,DefaultFrame.class,this);
            }
            //ExifInfo exif = new ExifInfo(inputStream);
            //exifInfoTextView.setText(exif.toString());
        } catch (Exception e) {
            Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
            Log.e("MainActivity", "Error loading image", e);
        }
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openGallery();
            } else {
                Toast.makeText(this, "需要存储权限以访问图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 辅助方法：根据 EXIF 信息旋转图片
    private Bitmap rotateBitmapIfRequired(Bitmap bitmap, Uri imageUri) throws Exception {
        InputStream exifInputStream = getContentResolver().openInputStream(imageUri);
        if (exifInputStream == null) return bitmap;
        ExifInfo exif = new ExifInfo(exifInputStream);
        switch (exif.getOrientation()) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return rotateBitmap(bitmap, 90);
            case ExifInterface.ORIENTATION_ROTATE_180:
                return rotateBitmap(bitmap, 180);
            case ExifInterface.ORIENTATION_ROTATE_270:
                return rotateBitmap(bitmap, 270);
            default:
                return bitmap;
        }
    }

    private Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degrees);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }
}
